package com.jse.jdbc;

import java.util.List;

import com.jse.Ioc;
import com.jse.json.JsonObject;

public class Sql {
	
	private Dao dao;
	private String type;
	private String[] fields;
	private String table;
	private StringBuilder where=new StringBuilder();
	private Object[] args;
	private String orderby;
	private String groupBy;
	private StringBuilder sb;
	private StringBuilder pg;//page 查询参数 如order by limit
	private Sql() {dao=Ioc.get("dao",Dao.class);}
	
	public Sql fields(String...fields) {this.fields=fields;return this;}
	public Sql table(String table) {this.table=table;return this;}
	public Sql where(String where) {this.where.append(" where ").append(where);return this;}
	public Sql and(String and) {this.where.append(" and ").append(and);return this;}
	public Sql param(Object...args) {this.args=args;return this;}
	public Sql orderBy(String by){ return this;};
	public Sql groupBy(String by){ return this;};
	public Sql desc(String desc){ return this;};
	
	public <T> List<T> findList(Class<T> c){
		return dao.queryForList(c, sb.toString(), args);
	}
	public <T> List<JsonObject> findList(){
		return dao.queryForList(sb.toString(), args);
	}
	public <T>T findById(Class<T> c,Object o){
		return dao.queryForObject(c,sb.toString(),o);
	}
	public <T>T find(Class<T> c){
		return dao.queryForObject(c,sb.toString(),args);
	}
	public <T>JsonObject find(){
		return dao.queryForMap(sb.toString(),args);
	}
	
	public String toString() {
		if(sb!=null)return sb.toString();
		sb=new StringBuilder(type).append(" ");
		if("select".equals(type)) {
			if(fields!=null&&fields.length>0) {
				sb.append(String.join(",", fields));
			}else {
				sb.append("*");
			}
			sb.append(" from ").append(table);
			if(where!=null)sb.append(where);
			return sb.toString();
		}
		return sb.toString();
	}
	public static Sql select(String...args) {
		var sql=new Sql();
		sql.type="select";
		if(args!=null&&args.length>0){
			sql.fields=args;
		}
		return sql;
	}

	public static void main(String[] args) {
		String sql=Sql.select("id","name","age").table("xxx").where("1=1").and("id=?").orderBy("id").param("1").toString();
		System.out.println(sql);
	}

}
